// 动画管理器
export class AnimationManager {
    constructor() {
        this.activeAnimations = [];
        this.animationQueue = [];
        this.isPlaying = false;
    }

    // 交换动画
    async swapAnimation(pos1, pos2, renderer, duration = 300) {
        return new Promise((resolve) => {
            const cell1Element = renderer.getCellElement(pos1.x, pos1.y);
            const cell2Element = renderer.getCellElement(pos2.x, pos2.y);

            if (!cell1Element || !cell2Element) {
                resolve();
                return;
            }

            // 获取单元格的位置信息
            const rect1 = cell1Element.getBoundingClientRect();
            const rect2 = cell2Element.getBoundingClientRect();

            // 计算移动距离
            const deltaX = rect2.left - rect1.left;
            const deltaY = rect2.top - rect1.top;

            // 设置动画样式
            const animationStyle = `transform ${duration}ms cubic-bezier(0.4, 0, 0.2, 1)`;
            
            cell1Element.style.transition = animationStyle;
            cell2Element.style.transition = animationStyle;
            cell1Element.style.zIndex = '100';
            cell2Element.style.zIndex = '100';

            // 执行交换动画
            cell1Element.style.transform = `translate(${deltaX}px, ${deltaY}px)`;
            cell2Element.style.transform = `translate(${-deltaX}px, ${-deltaY}px)`;

            // 动画完成后清理
            setTimeout(() => {
                cell1Element.style.transition = '';
                cell2Element.style.transition = '';
                cell1Element.style.transform = '';
                cell2Element.style.transform = '';
                cell1Element.style.zIndex = '';
                cell2Element.style.zIndex = '';
                resolve();
            }, duration);

            console.log(`交换动画: (${pos1.x},${pos1.y}) <-> (${pos2.x},${pos2.y})`);
        });
    }

    // 无效交换的回弹动画
    async bounceBackAnimation(pos1, pos2, renderer, duration = 200) {
        return new Promise((resolve) => {
            const cell1Element = renderer.getCellElement(pos1.x, pos1.y);
            const cell2Element = renderer.getCellElement(pos2.x, pos2.y);

            if (!cell1Element || !cell2Element) {
                resolve();
                return;
            }

            // 获取单元格的位置信息
            const rect1 = cell1Element.getBoundingClientRect();
            const rect2 = cell2Element.getBoundingClientRect();

            // 计算移动距离（较小的移动）
            const deltaX = (rect2.left - rect1.left) * 0.3;
            const deltaY = (rect2.top - rect1.top) * 0.3;

            // 设置动画样式
            const animationStyle = `transform ${duration}ms cubic-bezier(0.68, -0.55, 0.265, 1.55)`;
            
            cell1Element.style.transition = animationStyle;
            cell2Element.style.transition = animationStyle;

            // 执行回弹动画
            cell1Element.style.transform = `translate(${deltaX}px, ${deltaY}px)`;
            cell2Element.style.transform = `translate(${-deltaX}px, ${-deltaY}px)`;

            // 回弹回原位
            setTimeout(() => {
                cell1Element.style.transform = '';
                cell2Element.style.transform = '';

                setTimeout(() => {
                    cell1Element.style.transition = '';
                    cell2Element.style.transition = '';
                    resolve();
                }, duration);
            }, duration);

            console.log(`回弹动画: (${pos1.x},${pos1.y}) <-> (${pos2.x},${pos2.y})`);
        });
    }

    // 匹配消除动画
    async matchAnimation(matches, renderer, duration = 500) {
        return new Promise((resolve) => {
            if (!matches || matches.length === 0) {
                resolve();
                return;
            }

            const cellsToAnimate = [];
            
            matches.forEach(match => {
                match.cells.forEach(cell => {
                    const cellElement = renderer.getCellElement(cell.x, cell.y);
                    if (cellElement) {
                        cellsToAnimate.push(cellElement);
                        cellElement.classList.add('matching');
                    }
                });
            });

            // 动画完成后清理
            setTimeout(() => {
                cellsToAnimate.forEach(element => {
                    element.classList.remove('matching');
                });
                resolve();
            }, duration);

            console.log(`匹配动画: ${cellsToAnimate.length} 个单元格`);
        });
    }

    // 重力下落动画
    async fallAnimation(moves, renderer, duration = 400) {
        return new Promise((resolve) => {
            if (!moves || moves.length === 0) {
                resolve();
                return;
            }

            const animatedElements = [];

            moves.forEach(move => {
                const fromElement = renderer.getCellElement(move.from.x, move.from.y);
                const toElement = renderer.getCellElement(move.to.x, move.to.y);

                if (fromElement && toElement) {
                    // 计算下落距离
                    const distance = (move.to.y - move.from.y) * 100; // 假设每个单元格100px高

                    // 设置初始位置
                    toElement.style.transform = `translateY(-${distance}px)`;
                    toElement.style.transition = `transform ${duration}ms cubic-bezier(0.55, 0, 0.1, 1)`;
                    
                    animatedElements.push(toElement);

                    // 执行下落动画
                    requestAnimationFrame(() => {
                        toElement.style.transform = 'translateY(0)';
                    });
                }
            });

            // 动画完成后清理
            setTimeout(() => {
                animatedElements.forEach(element => {
                    element.style.transition = '';
                    element.style.transform = '';
                });
                resolve();
            }, duration);

            console.log(`下落动画: ${moves.length} 个移动`);
        });
    }

    // 新小鬼出现动画
    async newCellAnimation(newCells, renderer, duration = 200) {
        return new Promise((resolve) => {
            if (!newCells || newCells.length === 0) {
                resolve();
                return;
            }

            const animatedElements = [];

            newCells.forEach(cell => {
                const cellElement = renderer.getCellElement(cell.x, cell.y);
                if (cellElement) {
                    cellElement.classList.add('new-ghost');
                    animatedElements.push(cellElement);
                }
            });

            // 动画完成后清理
            setTimeout(() => {
                animatedElements.forEach(element => {
                    element.classList.remove('new-ghost');
                });
                resolve();
            }, duration + 600); // 包含bounce动画时间

            console.log(`新小鬼动画: ${newCells.length} 个单元格`);
        });
    }

    // 连锁动画执行
    async chainAnimation(animations) {
        for (const animation of animations) {
            await animation();
        }
    }

    // 并行动画执行
    async parallelAnimation(animations) {
        await Promise.all(animations.map(animation => animation()));
    }

    // 添加动画到队列
    queueAnimation(animationFn) {
        this.animationQueue.push(animationFn);
        
        if (!this.isPlaying) {
            this.playQueue();
        }
    }

    // 播放动画队列
    async playQueue() {
        this.isPlaying = true;

        while (this.animationQueue.length > 0) {
            const animation = this.animationQueue.shift();
            await animation();
        }

        this.isPlaying = false;
    }

    // 清空动画队列
    clearQueue() {
        this.animationQueue = [];
        this.isPlaying = false;
    }

    // 停止所有动画
    stopAllAnimations() {
        this.clearQueue();
        
        // 移除所有动画类
        const animatedElements = document.querySelectorAll('.matching, .falling, .new-ghost');
        animatedElements.forEach(element => {
            element.classList.remove('matching', 'falling', 'new-ghost');
            element.style.transition = '';
            element.style.transform = '';
            element.style.zIndex = '';
        });
    }

    // 检查是否有动画正在播放
    isAnimating() {
        return this.isPlaying || this.animationQueue.length > 0;
    }
}